//
//  CollectionViewController.m
//  DIYCoupon
//
//  Created by 张睿 on 16/12/29.
//  Copyright © 2016年 张睿. All rights reserved.
//

#import "CollectionViewController.h"
#import <Photos/Photos.h>
#import <Photos/PHCollection.h>
#import "ImageCollectionViewCell.h"
#import "EditViewController.h"
#import "UIView+SizeExt.h"

#define SCREEN6_SCALE ([UIScreen mainScreen].bounds.size.width /375)

@interface CollectionViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong)NSMutableArray<PHAssetCollection *>* array;
@property (nonatomic, strong)UICollectionView * collectionView;
@property (nonatomic, strong)NSMutableArray<PHAsset *> *assets;
@property (nonatomic, strong)UIImagePickerController * imagePickerController;

@end

@implementation CollectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"选择要分享的图片";
    
//    //初始化图片选择器
//    _imagePickerController=[[UIImagePickerController alloc]init];
//    _imagePickerController.delegate =self;
    //创建相册View
    [self setupCollectionViewUI];
    //创建barButton
    [self setupBarButton];
    //获取相册图片
    [self getAlbumsImages];
    

    _imagePickerController=[[UIImagePickerController alloc]init];
    _imagePickerController.delegate =self;

}

//========================华丽的分界线==========================
#pragma mark - 创建barButton -
- (void)setupBarButton{
    UIBarButtonItem * backItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(popToHomeView)];
    
    self.navigationItem.leftBarButtonItem = backItem;
    
    
}

#pragma mark - 取消选择,返回首页 -
- (void)popToHomeView{
    
    [self.navigationController popViewControllerAnimated:YES];
}

//========================华丽的分界线==========================
#pragma mark - 获取相册图片 -
- (void)getAlbumsImages{
    
    PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    self.array = [NSMutableArray arrayWithCapacity:0];
    
    [smartAlbums enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull collection, NSUInteger idx, BOOL *stop) {
//                NSLog(@"---相册名字:%@",collection.localizedTitle);
        //        [self transformAblumTitle:collection.localizedTitle];
        if ([collection.localizedTitle isEqualToString:@"Camera Roll"]) {
            [self.array addObject:collection];
        }
        
    }];
    
    //这是需要访问的相册内容集合
    PHFetchResult *result= [PHAsset fetchAssetsInAssetCollection:self.array[0] options:[[PHFetchOptions alloc] init]];
    
    self.assets = [NSMutableArray array];
    
    PHFetchOptions *option = [[PHFetchOptions alloc] init];
    //ascending 为YES时，按照照片的创建时间升序排列;为NO时，则降序排列
    option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
    
    //    PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:option];
    
    [result enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        PHAsset *asset = (PHAsset *)obj;
        //        NSLog(@"---照片名%@", [asset valueForKey:@"filename"]);
        [self.assets addObject:asset];
        NSLog(@"%@",self.assets);
    }];
    NSLog(@"---%@",self.assets);
    [self.collectionView layoutIfNeeded];
}

//========================华丽的分界线==========================
#pragma mark - 创建相册view -
- (void)setupCollectionViewUI{
    
    UICollectionViewFlowLayout * flowlayout = [[UICollectionViewFlowLayout alloc] init];
    flowlayout.itemSize = CGSizeMake(115 * SCREEN6_SCALE, 115 * SCREEN6_SCALE);
    flowlayout.minimumLineSpacing = 5 * SCREEN6_SCALE;
    flowlayout.minimumLineSpacing = 5 * SCREEN6_SCALE;
    flowlayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowlayout.sectionInset = UIEdgeInsetsMake(5 * SCREEN6_SCALE, 5 * SCREEN6_SCALE, 5 * SCREEN6_SCALE, 5 * SCREEN6_SCALE);
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowlayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerClass:[ImageCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.bounces = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    [self.view addSubview:self.collectionView];
}

#pragma mark - collection的数据方法 -
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    int count = (int)self.assets.count;
    int result = count + 1;
    
    return result;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    //仅显示缩略图，不控制质量显示
    /**
     PHImageRequestOptionsResizeModeNone, //默认质量
     PHImageRequestOptionsResizeModeFast, //加载预览图，即不太清晰
     PHImageRequestOptionsResizeModeExact //加载高清图片，会加载的比较慢
     */
    option.resizeMode = PHImageRequestOptionsResizeModeFast;
    option.networkAccessAllowed = YES;
    //param：targetSize 即你想要的图片尺寸，若想要原尺寸则可输入PHImageManagerMaximumSize
    if (indexPath.item == 0) {
        [cell.imageViewButton setImage:[UIImage imageNamed:@"img_camera"] forState:UIControlStateNormal];
    }else{
            PHAsset * asset = self.assets[indexPath.item - 1];
            
            [[PHCachingImageManager defaultManager] requestImageForAsset:asset targetSize:cell.bounds.size contentMode:PHImageContentModeAspectFit options:nil resultHandler:^(UIImage * _Nullable image, NSDictionary * _Nullable info) {
                //解析出来的图片
                [cell.imageViewButton setImage:image forState:UIControlStateNormal];
            }];
    }
    
    cell.imageViewButton.tag = indexPath.item;
    
    [cell.imageViewButton addTarget:self action:@selector(pushToCameraOrEditVC:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}
//========================华丽的分界线==========================
#pragma mark - 选择打开图片方式 -
-(void)pushToCameraOrEditVC:(UIButton *)button{
    if (button.tag == 0) {
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:_imagePickerController animated:YES completion:nil];
    }else{
        
        EditViewController * editVC = [EditViewController new];
        
        editVC.editImage = button.currentImage;
        
        [self.navigationController pushViewController:editVC animated:YES];
    }
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    [self dismissViewControllerAnimated:NO completion:^{
         EditViewController * editVC = [EditViewController new];
        //取得选择图片
        UIImage *selectedImage=[info objectForKey:UIImagePickerControllerOriginalImage];
        

        UIImage * test = [self scaleImage:selectedImage toScale:0.18];
//        selectedImage.size = CGSizeMake(width / 10, height / 10);
        
        editVC.editImage=test;
        [self.navigationController pushViewController:editVC animated:YES];
    }];
}

- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize{
    
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return scaledImage;
    
}

//========================华丽的分界线==========================

@end
